﻿using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YuuzleComic.DBUtility;

public partial class yzadmin_data_collect_xindm : YuuzleComic.Web.UI.ManagePage
{
    YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
    private JObject result = new JObject();
    protected string json = "";
    string baseUrl = "http://www.xindm.cn/e/action/ListInfo.php?page={0}&classid={1}&line={2}&tempid={3}&ph={4}&state={5}&infozm={6}&orderby={7}&myorder={8}&diqu={9}&ticai={10}";
    string domain = "http://www.xindm.cn";
    string ticai = "";
    string diqu = "";
    string infozm = "";
    string state = "";
    string orderby = "";
    int ph = 1;
    int tempid = 17;
    int line = 80;
    int classid = 8;
    int page = 0;
    int myorder = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "sync":
                    this.ProcessSync();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = new HtmlWeb();
            webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                string[] imgarr = doc.DocumentNode.SelectSingleNode("/html/script").InnerText.Split(new string[] { "(\"", "\",\"", "\")" }, StringSplitOptions.None);
                List<string> imglist = new List<string>(imgarr);
                imglist.RemoveAt(0);
                imglist.RemoveAt(imglist.Count - 1);
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.DocumentNode.SelectSingleNode("//span[@class='black_02']/b[1]").InnerText.Replace(doc.DocumentNode.SelectSingleNode("//table[1]//a[2]").InnerText, "").Trim();
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc + "/";
                zj.tps = imglist.Count;
                zj.tpurl = string.Join("|", imglist.ToArray());
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private string getUrl()
    {
        return string.Format(baseUrl, new object[] { page, classid, line, tempid, ph, state, infozm, orderby, myorder, diqu, ticai });
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = new HtmlWeb();
            webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//table[4]//table[2]//table[2]");
            HtmlNodeCollection propNodes = doc.DocumentNode.SelectNodes("//table[4]//table[2]//table[2]//table//tr");
            result.Add("mhmc", doc.DocumentNode.SelectSingleNode("//table[4]//b").InnerText);
            result.Add("mhfm", domain + doc.DocumentNode.SelectSingleNode("//table[4]//table[2]//img").Attributes["src"].Value);
            result.Add("zzmc", propNodes[10].SelectSingleNode("td[1]/a[1]").InnerText.Trim());
            result.Add("zm", propNodes[12].SelectSingleNode("td[1]/a[1]").InnerText.Remove(1));
            result.Add("mhtc", propNodes[14].SelectSingleNode("td[1]").InnerText.Substring(5));
            result.Add("mhbm", propNodes[16].SelectSingleNode("td[1]").InnerText.Substring(5));
            result.Add("zt", propNodes[2].SelectSingleNode("td[2]/img[1]").Attributes["src"].Value.Substring(10, 2));
            result.Add("classname", propNodes[0].SelectSingleNode("td[1]/a[1]").InnerText);
            result.Add("diqu", propNodes[6].SelectSingleNode("td[1]/a[1]") == null ? "" : propNodes[6].SelectSingleNode("td[1]/a[1]").InnerText);
            result.Add("time", propNodes[8].SelectSingleNode("td[1]").InnerText.Substring(5));
            result.Add("mhjj", doc.DocumentNode.SelectSingleNode("//span[@class='Grays_01']").InnerText);
            result.Add("mhjs", doc.DocumentNode.SelectSingleNode("//span[@class='Grays_01']").InnerHtml);
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = doc.GetElementbyId("mhlist").SelectNodes("table//li");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.SelectSingleNode("a").InnerText);
                    chapter.Add("zjurl", item.SelectSingleNode("a").Attributes["href"].Value);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessSync()
    {
        try
        {
            YuuzleComic.BLL.comics comicbll = new YuuzleComic.BLL.comics();
            YuuzleComic.BLL.diqu diqubll = new YuuzleComic.BLL.diqu();
            YuuzleComic.BLL.zz zzbll = new YuuzleComic.BLL.zz();
            YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
            HtmlWeb webClient = new HtmlWeb();
            webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HtmlDocument doc = webClient.Load(Request["mhurl"]);
            HtmlNodeCollection propNodes = doc.DocumentNode.SelectNodes("//table[4]//table[2]//table[2]//table//tr");
            #region 获取数据
            string mhmc = doc.DocumentNode.SelectSingleNode("//table[4]//b").InnerText;
            string mhfm = domain + doc.DocumentNode.SelectSingleNode("//table[4]//table[2]//img").Attributes["src"].Value;
            string zzmc = propNodes[10].SelectSingleNode("td[1]/a[1]").InnerText.Trim();
            string zm = propNodes[12].SelectSingleNode("td[1]/a[1]").InnerText.Remove(1);
            string mhtc = propNodes[14].SelectSingleNode("td[1]").InnerText.Substring(5);
            string mhbm = propNodes[16].SelectSingleNode("td[1]").InnerText.Substring(5);
            string zt = propNodes[2].SelectSingleNode("td[2]/img[1]").Attributes["src"].Value.Substring(10, 2);
            string classname = propNodes[0].SelectSingleNode("td[1]/a[1]").InnerText;
            string tj = propNodes[4].SelectSingleNode("td[1]/img[1]").Attributes["src"].Value.Split(new char[] { '_', '.' })[1];
            string diqu = propNodes[6].SelectSingleNode("td[1]/a[1]") == null ? "" : propNodes[6].SelectSingleNode("td[1]/a[1]").InnerText;
            string time = propNodes[8].SelectSingleNode("td[1]").InnerText.Substring(5);
            string mhjj = doc.DocumentNode.SelectSingleNode("//span[@class='Grays_01']").InnerText;
            string mhjs = doc.DocumentNode.SelectSingleNode("//span[@class='Grays_01']").InnerHtml; 
            #endregion

            DataSet ds;
            #region 处理地区问题
            int dqid = 0;
            ds = diqubll.GetList("diqu='" + diqu + "'");
            if (ds.Tables[0].Rows.Count == 1)
            {
                dqid = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]);
            }
            #endregion

            #region 处理作者问题
            int zzid = 39;

            if (!string.IsNullOrEmpty(zzmc) && zzmc != "未知")
            {
                zzid = zzbll.GetIdByName(zzmc);
                if (zzid == 0)
                {
                    YuuzleComic.Model.zz zzobj = new YuuzleComic.Model.zz();
                    zzobj.zzmc = zzmc;
                    zzobj.zzjs = "<h2 class=\"blue\">" + zzmc + "漫画全集</h2>";
                    zzobj.dqid = dqid;
                    zzobj.zztp = "none.jpg";
                    zzobj.zm = YuuzleComic.Common.Chs2Spell.GetHeadOfChs(zzmc.Substring(0, 1));
                    zzid = zzbll.Add(zzobj);
                }
            }
            #endregion

            #region 处理漫画情况
            int comicid = 0;
            YuuzleComic.Model.comics comics = new YuuzleComic.Model.comics();
            comics.classid = 1;
            comics.mhmc = mhmc;//漫画名称
            comics.zzid = zzid;//作者
            comics.dqid = dqid; //地区
            comics.zm = zm;//首字母
            comics.zt = zt == "完结"; //是否完结
            comics.tj = tj == "i5"; //是否推荐
            comics.mhjs = mhjs.Replace("(本漫画内容介绍由xindm.cn整理提供)", ""); //漫画介绍
            comics.mhjj = YuuzleComic.Common.Input.GetSubString(YuuzleComic.Common.Input.FilterHTML(comics.mhjs).Trim(), 300, "…");
            comics.mhtc = mhtc.Replace("&nbsp;", " ").Trim();
            comics.mhbm = mhbm;
            if (!comicbll.Exists(mhmc))
            {
                #region 添加漫画
                comics.adddate = DateTime.Now;
                ds = DbHelperSQL.Query("select top(1) text from segment order by newid()");
                comics.mhjs = comics.mhjs.Trim() + "<br/>" + ds.Tables[0].Rows[0][0].ToString();
                comicid = comicbll.Add(comics);
                #endregion
                DbHelperSQL.ExecuteSql("insert into comics_zz (cid,zzid) values (" + comicid + "," + zzid + ")");
            }
            else
            {
                ds = comicbll.GetList("mhmc = '" + mhmc.Replace("'", "''") + "'");
                if (ds.Tables[0].Rows.Count == 1)
                {
                    comicid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                    DbHelperSQL.ExecuteSql("update comics set tj=" + (comics.tj ? 1 : 0) + ",zt=" + (comics.zt ? 1 : 0) + ",mhtc='" + comics.mhtc + "' where ID=" + comicid);
                }
            }
            #region 保存封面
            string filename = comicid + System.IO.Path.GetExtension(mhfm);
            if (!System.IO.File.Exists(Server.MapPath("~/cpic/" + filename)))
            {
                YuuzleComic.Common.XindmSession.saveImage(mhfm, Server.MapPath("~/cpic/" + filename));
            }
            DbHelperSQL.ExecuteSql("update comics set mhfm='" + filename + "' where ID=" + comicid);
            #endregion
            #endregion

            List<string> zjurlList = new List<string>();
            List<string> zjmcList = new List<string>();
            HtmlNodeCollection nodes = doc.GetElementbyId("mhlist").SelectNodes("table//li");
            if (nodes != null)
            {
                foreach (HtmlNode node in nodes)
                {
                    string zjmc = node.SelectSingleNode("a").InnerText.Trim();
                    if (!zjbll.Exists(zjmc,comicid))
                    {
                        zjmcList.Add(zjmc);
                        zjurlList.Add(node.SelectSingleNode("a").Attributes["href"].Value);
                    }
                }
            }
            zjurlList.Reverse(); zjmcList.Reverse();
            foreach (string zjurl in zjurlList)
            {
                doc = webClient.Load(zjurl);
                string[] imgarr = doc.DocumentNode.SelectSingleNode("/html/script").InnerText.Split(new string[] { "(\"", "\",\"", "\")" }, StringSplitOptions.None);
                List<string> imglist=new List<string>(imgarr);
                imglist.RemoveAt(0);
                imglist.RemoveAt(imglist.Count - 1);
                YuuzleComic.Model.zj zjobj = new YuuzleComic.Model.zj();
                zjobj.cid = comicid;
                zjobj.zjmc = zjmcList[zjurlList.IndexOf(zjurl)];
                zjobj.tpadd = "";
                zjobj.tps = imglist.Count;
                zjobj.tpf = 0;
                zjobj.isdownload = false;
                zjobj.time = DateTime.Now;
                zjobj.tpurl = string.Join("|", imglist.ToArray());
                string url = imglist[0];
                if (!string.IsNullOrEmpty(url) && url.Length > 1)
                {
                    string[] urlArr = url.Substring(0, url.LastIndexOf("/")).Split('/');
                    for (int i = 2; i < urlArr.Length; i++)
                    {
                        zjobj.tpadd += System.Web.HttpUtility.UrlDecode(urlArr[i]) + "/";
                    }
                }

                string zjmc_temp = zjobj.zjmc;
                foreach (string s in new string[] { "清晰版", "KC", "正式版" })
                {
                    zjmc_temp = zjmc_temp.Replace(s, "").Trim();
                }
                if (zjbll.ExistsAdd(zjobj.tpadd, comicid))
                {
                    DbHelperSQL.ExecuteSql("update zj set zjmc='" + zjobj.zjmc + "' where tpadd='" + zjobj.tpadd + "' and cid=" + comicid);
                }
                else if (zjbll.Exists(zjmc_temp, comicid))
                {
                    DataSet dszj = zjbll.GetList("zjmc='" + zjmc_temp + "' and cid=" + comicid);
                    if (dszj.Tables[0].Rows.Count == 1)
                    {
                        zjobj.id = Convert.ToInt32(dszj.Tables[0].Rows[0]["id"]);
                        zjbll.Update(zjobj);
                    }
                }
                else
                {
                    zjbll.Add(zjobj);
                }
            }

            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            ticai = HttpUtility.UrlEncode(Request["ticai"], System.Text.Encoding.GetEncoding("GB2312"));
            diqu = HttpUtility.UrlEncode(Request["diqu"], System.Text.Encoding.GetEncoding("GB2312"));
            infozm = Request["infozm"];
            state = HttpUtility.UrlEncode(Request["state"], System.Text.Encoding.GetEncoding("GB2312"));
            orderby = Request["orderby"];
            page = Convert.ToInt32(Request["page"]) - 1;
            HtmlWeb webClient = new HtmlWeb();
            webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HtmlDocument doc = webClient.Load(this.getUrl());
            int total = Convert.ToInt32(doc.DocumentNode.SelectSingleNode("//span[@class=\"page-list1\"]/span[1]").InnerHtml.Split(new string[] { "共", "部" }, StringSplitOptions.None)[1]);
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[starts-with(@class,'reminderindex1')]/ul[1]/li");
            JArray data = new JArray();
            foreach (HtmlNode node in nodes)
            {
                JObject jo = new JObject();
                jo.Add("mhmc", node.SelectSingleNode("div[1]/span[1]/a[1]").InnerText);
                jo.Add("mhurl", node.SelectSingleNode("div[1]/span[1]/a[1]").Attributes["href"].Value);
                if (node.SelectSingleNode("div[1]/span[2]/a[1]") != null)
                {
                    jo.Add("zjmc", node.SelectSingleNode("div[1]/span[2]/a[1]").InnerText);
                    jo.Add("zjurl", node.SelectSingleNode("div[1]/span[2]/a[1]").Attributes["href"].Value);
                }
                jo.Add("date", node.SelectSingleNode("div[1]/span[3]").InnerText);
                data.Add(jo);
            }
            result.Add("data", data);
            result.Add("total", total);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }
}